package com.tomicalab.mobiletoken.ckca;

import iaik.pkcs.pkcs11.wrapper.PKCS11Exception;

import com.tomicalab.mobiletoken.ckca.utils.Constant;
import com.tomicalab.mobiletoken.ckca.utils.CustomProgressDialog;
import com.tomicalab.mobiletoken.ckca.utils.P11Other;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;

public class ChangePIN extends Activity{
	private EditText etOldPin;
	private EditText etNewPin;
	private EditText etConfirmPin;
	private ImageButton iBChangePin;
	
	private Context context;
	private Resources res;
	
	private static CustomProgressDialog progressDialog;
	private static handler handler;
	
	public class handler extends Handler {
		String oldPassword, newPassword;
		public void sleep(long delayMillis, int msgID, Object obj) {
            this.removeMessages(msgID);
            Message msg = new Message();
            msg.what = msgID;
            msg.obj  = obj;
            sendMessageDelayed(msg, delayMillis);
        }
		
		public void sleep(long delayMillis, int msgID, String oldPassword, String newPassword) {
            this.removeMessages(msgID);
            Message msg = new Message();
            msg.what = msgID;
            msg.obj  = oldPassword;
            sendMessageDelayed(msg, delayMillis);
            this.oldPassword = oldPassword;
            this.newPassword = newPassword;
        }
		
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case Constant.SHOWPROGRESSDIALOG:
				Log.e(Constant.Debug, "SHOWPROGRESSDIALOG");
				progressDialog.show();
				super.handleMessage(msg);
				break;
			case Constant.CLOSEPROGRESSDIALOG:
				progressDialog.dismiss();
				super.handleMessage(msg);
				break;
			case Constant.SHOWERRINFO:
				if (null != msg.obj)
				{
					if(msg.obj.toString().compareTo(res.getString(R.string.inform_handset_connectfail))==0)
					{
						String title, button;
			    		button = res.getString(R.string.inform_button_OK);
						title = res.getString(R.string.inform_title);
						new Builder(context)
				    	.setTitle(title)
				    	.setMessage(msg.obj.toString())
				    	.setPositiveButton(button, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								finish();
							}
						}).show();
					}
					else
						Constant.showMessage(msg.obj.toString(), context, res);
				}
				super.handleMessage(msg);
				break;
			case Constant.CHANGEPIN:
				changePin(oldPassword, newPassword);
				super.handleMessage(msg);
				break;
			}			
		}
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_changpin);
		Log.i(Constant.Debug, "onCreate ChangePIN");
		context = this;
		res = this.getResources();
		
		progressDialog = new CustomProgressDialog(context);
		progressDialog.setCancelable(false);
		handler = new handler();
		
		etOldPin = (EditText) findViewById(R.id.et_oldpin);
		etNewPin = (EditText) findViewById(R.id.et_newpin);
		etConfirmPin = (EditText) findViewById(R.id.et_confirmpin);
		iBChangePin = (ImageButton) findViewById(R.id.btn_changepin_ok);
		
		iBChangePin.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Constant.hideSoftKeyboard(ChangePIN.this, arg0);
				if(P11Other.isTokenPlugned == 0)
				{
					Constant.showMessage(res.getString(R.string.inform_handset_plugout), context, res);
				}
				else
				{
					if(P11Other.isLoadlib == 0)
					{
						Constant.showMessage(res.getString(R.string.inform_handset_loadLib), context, res);
					}
					else
					{
						String oldpin = etOldPin.getText().toString();
						String newpin = etNewPin.getText().toString();
						String confirmpin = etConfirmPin.getText().toString();
						if(oldpin.length() == 0 || newpin.length() == 0 || confirmpin.length() == 0)
						{
							Constant.showMessage(res.getString(R.string.inform_input_notnull), context, res);
						}
						else if(newpin.compareTo(confirmpin) != 0)
						{
							Constant.showMessage(res.getString(R.string.inform_input_newandconfirm), context, res);
						}
						else
						{
							progressDialog.setShowInfo(res.getString(R.string.inform_changepin_wait));
							handler.sleep(0, Constant.SHOWPROGRESSDIALOG, "");
							handler.sleep(100, Constant.CHANGEPIN, oldpin, newpin);
						}
						etOldPin.setText("");
						etNewPin.setText("");
						etConfirmPin.setText("");
					}
				}
			}
		});
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Log.i(Constant.Debug, "onResume ChangePIN");
	}
	private void changePin(final String oldpin, final String newpin)
	{
		new Thread() {
			public void run() {
				try {
					long rv = P11Other.changePassword(oldpin, newpin);
					Log.d(Constant.Debug, "status changepin: "+rv);
					if (rv == 0) {
						handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "");
						String msg;
						msg = res.getString(R.string.inform_changepin_result);
						handler.sleep(100, Constant.SHOWERRINFO, msg);
					}
	    			else if (rv == 0x6983 || rv == 0x63C0) {
	    				handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "");
						String msg;
						msg = "Error: 0x6983 (0x63C0)";
						handler.sleep(10, Constant.SHOWERRINFO, msg);
						
					} else if ((rv & 0x63C0) == 0x63C0) {
						handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "");
						String msg;
						msg = res.getString(R.string.inform_changepin_error2);
						handler.sleep(10, Constant.SHOWERRINFO, msg);
					}  else {
						handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "");
						String msg;
						msg = res.getString(R.string.inform_changepin_error1);
						handler.sleep(10, Constant.SHOWERRINFO, msg);
					}
				} catch (PKCS11Exception e) {
					e.printStackTrace();
					handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "");
					String msg;
					msg = res.getString(R.string.inform_changepin_error1);
					handler.sleep(10, Constant.SHOWERRINFO, msg);
				}
			}
		}.start();
	}

}
